package com.relax.mybatis.encrypt.algorithm;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.jasypt.util.text.AES256TextEncryptor;

import com.relax.mybatis.constant.Algorithm;

/**
 * @author relax
 * @date 2022/07/05
 * @desc 混合算法加密
 */
public class HybridAlgorithm {

    private static StrongPasswordEncryptor strongPasswordEncryptor;

    public static StrongPasswordEncryptor getStrongPasswordEncryptor() {
        if (null == strongPasswordEncryptor)
            strongPasswordEncryptor = new StrongPasswordEncryptor();
        return strongPasswordEncryptor;
    }

    public static String encrypt(Algorithm algorithm, boolean encrypt, String data, String password) {
        if (Algorithm.PBEWithHMACSHA512AndAES_256 == algorithm) {
            AES256TextEncryptor encryptor = new AES256TextEncryptor();
            encryptor.setPassword(password);
            return encrypt ? encryptor.encrypt(data) : encryptor.decrypt(data);
        }
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        encryptor.setPassword(password);
        encryptor.setAlgorithm(algorithm.name());
        return encrypt ? encryptor.encrypt(data) : encryptor.decrypt(data);
    }

}
